import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/zapi-allin-sys',
  headers: {
    'Content-Type': 'application/json',
  },
})

// 防止浏览器对接口 GET 请求使用缓存（出现 304 from disk cache）
api.interceptors.request.use((config) => {
  // 统一加上 no-cache 头
  config.headers = {
    ...(config.headers || {}),
    'Cache-Control': 'no-cache',
    Pragma: 'no-cache',
  }
  // GET 请求添加时间戳参数，避免命中缓存
  if ((config.method || 'get').toLowerCase() === 'get') {
    const params = new URLSearchParams(config.params || {})
    params.set('_t', Date.now().toString())
    config.params = Object.fromEntries(params.entries())
  }
  return config
})

export const uploadDocument = ({ file, path = '', description = '', uploadUserId, uploadUsername }) => {
  const formData = new FormData()
  formData.append('file', file)
  if (path !== undefined && path !== null) formData.append('path', path)
  if (description !== undefined && description !== null) formData.append('description', description)
  if (uploadUserId !== undefined && uploadUserId !== null) formData.append('uploadUserId', uploadUserId)
  if (uploadUsername !== undefined && uploadUsername !== null) formData.append('uploadUsername', uploadUsername)

  return api.post('/file/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
}

export const getDocumentEditConfig = (documentId) => {
  return api.get(`/api/documents/edit-config/${documentId}`)
}

export const getFileList = (params) => {
  return api.get('/file/list', { params })
}

export function forceSaveDocument(key) {
  return api.post('/api/documents/force-save', { key })
}

export default api
